//
//  XMGKeyboardTextView.swift
//  01-表情键盘的封装
//
//  Created by apple on 15/12/11.
//  Copyright © 2015年 xiaomage. All rights reserved.
//

import UIKit

class XMGKeyboardTextView: UITextView {

    func insertEmoticon(emoticon : XMGKeyboardEmoticon) {
        // 1.emoji表情
        if let codeStr = emoticon.emoticonStr {
            
            // 1.获取当前的光标所在的位置
            let range = selectedTextRange!
            
            // 2.替换光标位置的内容
            replaceRange(range, withText: codeStr)
            
            return
        }
        
        // 2.普通表情
        if let pngPath = emoticon.pngPath {
            
            // 2.1.根据当前的文字创建一个可变的属性字符串
            let strM = NSMutableAttributedString(attributedString: attributedText)
            
            // 2.2.获取光标所在的位置
            let range = selectedRange
            
            // 2.3.在光标所在的位置替换表情
            let attachment = XMGKeyboardAttachment()
            attachment.chs = emoticon.chs
            let fontHeight = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            attachment.image = UIImage(contentsOfFile: pngPath)
            let emoticonStr = NSAttributedString(attachment: attachment)
            strM.replaceCharactersInRange(range, withAttributedString: emoticonStr)
            
            // 2.4.将拼接后的属性字符串显示出来
            attributedText = strM
            
            // 2.5.让光标回到表情后面
            selectedRange = NSRange(location: range.location + 1, length: 0)
            
            // 2.6.将属性文字的大小重置
            font = UIFont.systemFontOfSize(18)
            
            return
        }
        
        // 3.删除按钮
        if emoticon.isRemoveButton {
            deleteBackward()
        }
    }
    
    func emoticonStr() -> String {
        let range = NSRange(location: 0, length: attributedText.length)
        
        var emoticonStr = String()
        
        attributedText.enumerateAttributesInRange(range, options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict : [String : AnyObject], range, _) -> Void in
            // 表情可以将文字分开成多个字典
            // 如果是表情字典,则里面有NSAttachment的key和对应的值
            if let attrachment = dict["NSAttachment"] as? XMGKeyboardAttachment {
                emoticonStr += attrachment.chs!
            } else {
                let textStr = (self.attributedText.string as NSString).substringWithRange(range)
                emoticonStr += textStr
            }
        }
        
        return emoticonStr
    }

}
